interface Point {
    posX: number,
    posY: number,
}

interface Drag {
    dragStart(): void,
    dragMove(): void,
    dragEnd(): void,
}

class DragEle implements Point, Drag {
    public target: HTMLElement
    public posX: number
    public posY: number

    constructor(ele: HTMLElement) {
        this.target = ele;
    }
    init() {
        // this -> 调用此方法的实例化对象
        this.randColor();
        this.dragStart();
    }
    dragStart() {
        var _this = this;
        this.target.onmousedown = function (evt: MouseEvent) {
            var posX = evt.offsetX;
            var posY = evt.offsetY;
            console.log(posX, posY);

            // console.log(this); // 指向绑定事件的元素

            _this.posX = posX;
            _this.posY = posY;
            console.log(_this);

            _this.target.style.zIndex = "99999";

            _this.dragMove(); // 先按下再移动
            _this.dragEnd();  // 按下时绑定清除
        }
    }
    dragMove() {
        document.onmousemove = (evt: MouseEvent) => {
            var x = evt.pageX - this.posX;
            var y = evt.pageY - this.posY;

            this.target.style.left = x + "px";
            this.target.style.top = y + "px";


        }
    }
    dragEnd() {
        document.onmouseup = function () {
            document.onmousemove = null;
            this.target.style.zIndex = 0;
        }.bind(this);
    }
    randColor(): void {
        var colorStr = "#";
        for (var i = 0; i < 6; i++) {
            var num = Math.round(Math.random() * 16);
            var char = num.toString(16);
            colorStr += char;
        }
        this.target.style.backgroundColor = colorStr;
    }

}